<template>
  <page-wrap hideTab :title="positionName" back stayStill>
    <view class="detail" v-show="loaded">
      <view class="preview-box">
        <view class="pre-img-wrap">
          <template v-for="(item, index) in previewImgList">
            <image
              :src="item"
              :key="index"
              mode="widthFix"
              class="preview-img"
            ></image>
          </template>
          <!-- 只有未购买才会出现的的提示 -->
          <template v-if="isBuy == 'false'">
            <view
              v-if="leftValue == 0"
              class="buy-then-check"
              @click="handlePaySubscribe"
              >剩余{{ leftPageNum }}页，请购买后查看
              <view class="drop-down"></view>
            </view>
            <view
              v-if="leftValue > 0"
              class="buy-then-check"
              @click="handlePreviewReport"
              >查看剩余{{ leftPageNum }}页
              <view class="drop-down"></view>
            </view>
          </template>
          <template v-else> </template>
        </view>
      </view>
    </view>
    <!-- 没有购买 -->
    <template v-if="isBuy == 'false'">
      <!-- 剩余权益数目为0，则显示购买按钮 -->
      <template v-if="leftValue <= 0">
        <view class="buyButton" v-if="showPackageBtn == 'true'">
          <view class="buyPackage" @click="showBuyList">
            职途权益套餐
            <view class="least-price" v-if="showLeastPrice == 0"></view>
          </view>
          <view class="buySingle" @click="handlePaySubscribe"
            >购买该报告 <text style="margin-left: 24rpx">￥20/份</text>
          </view>
        </view>
        <view class="btn-box" v-else>
          <view class="check-btn" @click="handlePaySubscribe"
            >购买该报告 <text style="margin-left: 24rpx">￥20/份</text>
          </view>
        </view>
      </template>
      <!-- 如果剩余权益数目大于0，就显示查看报告按钮，弹出消耗权益弹窗 -->
      <template v-if="leftValue > 0">
        <view class="buyButton" v-if="showPackageBtn == 'true'">
          <view class="buyPackage" @click="showBuyList">
            职途权益套餐
            <view class="least-price" v-if="showLeastPrice == 0"></view>
          </view>
          <view class="buySingle" @click="handlePreviewReport">查看报告 </view>
        </view>
        <view class="btn-box" v-else>
          <view class="check-btn" @click="handlePreviewReport">查看报告 </view>
        </view>
      </template>
    </template>
    <ShoppingCar
      v-if="showPopup"
      :showPopup="showPopup"
      @closePopup="closePopup"
    ></ShoppingCar>
    <u-modal
      v-model="showTips"
      :show-title="false"
      :show-cancel-button="true"
      :show-confirm-button="true"
      :cancel-style="cancelStyle"
      :confirm-style="confirmStyle"
      @confirm="handleConfirm"
    >
      <view class="slot-content">
        <view class="question">是否消耗一次查看次数？</view>
        <view class="left-num">查看次数剩余{{ leftValue }}</view>
      </view>
    </u-modal>
  </page-wrap>
</template>

<script>
import {
  getReportImage,
  addCartAndToOrder,
  addZhituPayOrder,
  getRightSingleProduct,
  careerQuizRelReportByRight
} from '@/api/modules/career';
import ShoppingCar from './components/ShoppingCar.vue';

export default {
  components: { ShoppingCar },
  data() {
    return {
      ylPositionId: '',
      positionName: '职业报告详情',
      previewImgList: [],
      loaded: false,
      currentPackage: 0,
      showPopup: false,
      isBuy: 'false', // 判断当前报告是否被购买
      wholeReport: [],
      rightSingleProductId: '',
      rightProductId: '',
      leftValue: 0,
      cancelStyle: {
        fontWeight: '600',
        fontSize: '28rpx',
        color: '#999999'
      },
      confirmStyle: {
        fontWeight: '600',
        fontSize: '28rpx',
        color: ' #F75A3E'
      },
      showTips: false,
      leftPageNum: 0, // 报告剩余页数
      showPackageBtn: 'false',
      showLeastPrice: 0
    };
  },
  created() {
    uni.getProvider({
      service: 'payment',
      success: (res) => {
        this.provider = res.provider;
      }
    });
  },
  onLoad(opt) {
    this.ylPositionId = opt.ylPositionId || '';
    this.positionName = opt.positionName || '';
    this.isBuy = opt.isBuy;
    this.showPackageBtn = opt.showPackageBtn;
    this.showLeastPrice = opt.showLeastPrice;
    this.leftValue = +opt.leftValue || 0;
  },
  onShow() {
    this.getRightSingleProductFn();
  },
  mounted() {
    this.getReportImageFn();
    this.personId = uni.getStorageSync('person-id').slice(2);
  },
  methods: {
    handlePreviewReport() {
      this.showTips = true;
    },
    async careerQuizRelReportByRightFn() {
      const params = {
        dataId: this.personId,
        dataType: 1, // 职途职业测评
        templateCode: 'career_report',
        ylPositionId: this.ylPositionId
      };
      await careerQuizRelReportByRight(params);
    },
    async getRightSingleProductFn() {
      const params = {
        cardType: uni.getStorageSync('cardType'),
        rightId: this.rightId
      };
      const res = await getRightSingleProduct(params);
      if (res.code == 200) {
        this.rightSingleProductId = res.data.mallProductId;
        this.rightProductId = res.data.id;
      }
    },
    closePopup() {
      this.showPopup = false;
    },
    showBuyList() {
      this.showPopup = true;
      this.currentPackage = 0;
    },
    //1.生成订单
    addCartAndToOrder() {
      uni.showLoading({
        title: '生成订单中...',
        mask: true
      });
      addCartAndToOrder({
        orderType: 'ZT_SERVICE',
        mallProductId: this.rightSingleProductId,
        channelType: 80,
        sourceType: 3,
        personId: this.personId,
        rightId: this.rightId,
        cardType: this.cardType,
        orderCondition: {
          rightProductId: this.rightProductId
        }
      })
        .then((res) => {
          console.log(res);
          if (res.code == 200) {
            this.addZhituPayOrder(res.data);
          } else {
            uni.hideLoading();
            uni.showToast({
              title: res.status_desc || '生成订单失败',
              icon: 'none',
              duration: 2000
            });
          }
        })

        .catch((err) => {
          uni.hideLoading();
          uni.showToast({
            title: err.status_desc || '生成订单失败',
            icon: 'none',
            duration: 2000
          });
        })
        .finally(() => {});
    },
    //2.通过订单获取支付信息
    addZhituPayOrder(data) {
      addZhituPayOrder({
        ...data,
        orderType: 'ZT_SERVICE',
        wayCode: 'WX_LITE',
        personId: this.personId,
        personName: uni.getStorageSync('personName'),
        openid: uni.getStorageSync('openid')
      })
        .then((res) => {
          console.log(res);
          if (res.code == 200) {
            this.requestPayment(res.data);
          } else {
            uni.hideLoading();
            uni.showToast({
              title: res.status_desc || '获取商品信息失败',
              icon: 'none',
              duration: 2000
            });
          }
        })
        .catch((err) => {
          uni.hideLoading();
          uni.showToast({
            title: err.status_desc || '获取商品信息失败',
            icon: 'none',
            duration: 2000
          });
        })
        .finally(() => {});
    },
    //3.使用支付信息调用支付
    requestPayment(data) {
      uni.hideLoading();
      if (this.provider.indexOf('wxpay') < 0) {
        return;
      }
      const payData = JSON.parse(data.payData);
      uni.requestPayment({
        provider: this.provider[0],
        timeStamp: payData.timeStamp,
        nonceStr: payData.nonceStr,
        package: payData.package,
        signType: payData.signType,
        paySign: payData.paySign,
        success: (res) => {
          this.isBuy = 'true';
          this.previewImgList = this.wholeReport;
          this.careerQuizRelReportByRightFn();
        },
        fail: (err) => {
          uni.showToast({
            title: '支付失败,请您重新支付',
            icon: 'none',
            duration: 3000
          });
        }
      });
    },
    //还要订阅一下支付，退费相关信息
    handlePaySubscribe() {
      uni.requestSubscribeMessage({
        tmplIds: ['neXhGgVHV7JGNqQZOfu30pQmQcZIFUy73CBvK5OF98M'],
        complete: (res) => {
          Object.keys(res).forEach((key) => {
            if (res[key] === 'accept') {
              this.addCartAndToOrder();
            }
          });
        }
      });
    },
    handleConfirm() {
      this.isBuy = 'true';
      this.previewImgList = this.wholeReport;
      this.careerQuizRelReportByRightFn();
      this.showTips = false;
    },
    getReportImageFn() {
      uni.showLoading({
        title: '加载中...'
      });
      const params = {
        ylPositionId: this.ylPositionId,
        templateCode: 'career_report'
      };
      setTimeout(() => {
        uni.hideLoading();
      }, 2300);
      getReportImage(params).then((res) => {
        if (res.code == 200) {
          let imgList = [];
          res.data.forEach((item) => {
            imgList.push(item.oneFileImg);
          });
          if (this.isBuy == 'true') {
            this.previewImgList = imgList;
          } else {
            this.previewImgList = [imgList[0]]; // 如果没买只给用户看一页
            this.wholeReport = imgList;
            this.leftPageNum = this.wholeReport.length - 1;
          }
          this.loaded = true;
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
$img-base-careerPath: $img-base + 'careerPath/';

.detail {
  background-color: #f4f6f8;

  .preview-box {
    .pre-img-wrap {
      position: relative;
      margin: 32rpx 24rpx 0 24rpx;

      .preview-img {
        margin-bottom: 20rpx;
        border-radius: 16rpx;
      }

      .check-more {
        position: absolute;
        z-index: 2;
        bottom: 0;
        width: 100%;
        padding: 196rpx 0 12rpx 0;
        font-size: 30rpx;
        text-align: center;
        color: #f75a3e;
        background-image: url($img-base + 'report/mask2.png');
        background-size: 100% 100%;

        u-icon {
          margin-left: 8rpx;
        }
      }

      .buy-then-check {
        width: 100%;
        height: 44rpx;
        font-family: PingFangSC, PingFang SC;
        font-weight: 400;
        font-size: 30rpx;
        color: #f75a3e;
        line-height: 44rpx;
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: center;

        .drop-down {
          width: 36rpx;
          height: 36rpx;
          background-image: url($img-base-careerPath + 'dropDown.png');
          background-repeat: no-repeat;
          background-size: 100% 100%;
        }
      }

      image {
        width: 100%;
      }
    }

    .pre-img {
      width: 100%;
      height: 100%;
      border-radius: 16rpx;
    }

    .preview-btn {
      position: absolute;
      top: 45%;
      left: 50%;
      transform: translate(-50%, -50%);
      width: 342rpx;
      height: 160rpx;
      text-align: center;
      line-height: 140rpx;
      background-image: url($img-base + 'report/react.png');
      background-size: 100% 100%;
      background-position: center 10%;
      font-size: 28rpx;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #ff6969;

      .icon-book {
        width: 36rpx;
        height: 36rpx;
        margin-right: 10rpx;
        background-image: url($img-base + 'report/book.png');
      }
    }
  }

  .recommend {
    &-title {
      margin-left: 32rpx;
      margin-bottom: 28rpx;
      font-size: $uni-font-size-big;
      color: #222222;
    }
  }
}

.buyButton {
  position: fixed;
  bottom: 76rpx;
  left: 0;
  display: flex;
  align-items: center;
  justify-content: space-around;
  width: calc(100vw - 80rpx);
  height: 100rpx;
  margin: 0 40rpx;
  z-index: 999;

  .buyPackage,
  .buySingle {
    width: 328rpx;
    height: 88rpx;
    border-radius: 44rpx;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
  }

  .buyPackage {
    position: relative;
    font-family: PingFangSC, PingFang SC;
    font-weight: 500;
    font-size: 28rpx;
    color: #ffe0a1;
    line-height: 36rpx;
    background: linear-gradient(270deg, #38342b 0%, #413f3f 100%);

    .least-price {
      position: absolute;
      width: 132rpx;
      height: 34rpx;
      background-image: url($img-base-careerPath + 'jobtestLeastPrice.png');
      background-repeat: no-repeat;
      background-size: 100% 100%;
      top: -16rpx;
      left: 64rpx;
    }
  }

  .buySingle {
    font-family: PingFang-SC, PingFang-SC;
    /* font-weight: 800; */
    font-size: 32rpx;
    color: #ffffff;
    line-height: 44rpx;
    background-color: #ff711e;

    view {
      font-size: 24rpx;
    }
  }
}

.btn-box {
  width: calc(100vw - 64rpx);
  display: flex;
  justify-content: center;
  position: fixed;
  bottom: 76rpx;
  left: 32rpx;
  .check-btn {
    color: #ffffff;
    font-size: 32rpx;
    font-weight: 600;
    width: 100%;
    height: 88rpx;
    line-height: 88rpx;
    text-align: center;
    border-radius: 44rpx;
    background: #f75a3e;
  }
}

.slot-content {
  text-align: center;
  padding: 40rpx 60rpx 42rpx 60rpx;
  .question {
    font-weight: 600;
    font-size: 36rpx;
    color: #000000;
    line-height: 50rpx;
    margin-bottom: 18rpx;
  }
  .left-num {
    font-size: 28rpx;
    color: #f75a3e;
    line-height: 40rpx;
    text-align: center;
  }
}
</style>
